<template>
  <view class="page-content">
    <!-- 搜索框 -->
    <view class="search-section">
      <input 
        v-model="searchKeyword" 
        class="search-input" 
        placeholder="搜索项目名称或客户名称" 
        @confirm="onSearch"
      />
      <button class="search-btn" @click="onSearch">搜索</button>
    </view>
    
    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view 
        class="filter-tab" 
        :class="{ active: currentFilter === filter.value }"
        v-for="filter in filterTabs" 
        :key="filter.value"
        @click="onFilterChange(filter.value)"
      >
        {{ filter.label }}
      </view>
    </view>

    <!-- 项目列表 -->
    <view class="project-list">
      <view 
        class="project-item" 
        v-for="item in projectList" 
        :key="item.id"
        @click="viewDetail(item)"
      >
        <view class="item-header">
          <text class="project-name">{{ item.project_name || '未知项目' }}</text>
          <text class="status-text" :class="{ 'signed': item.status === '已签约', 'error': item.status === '异常' }">{{ getStatusText(item.status) }}</text>
        </view>
        
        <view class="item-content">
          <view class="info-row">
            <text class="label">客户名：</text>
            <text class="value">{{ item.customer_name || '未知客户' }}</text>
          </view>
          <view class="info-row">
            <text class="label">负责人电话：</text>
            <text class="value">{{ item.manager_phone || '未知' }}</text>
          </view>
          <view class="info-row">
            <text class="label">合同编号：</text>
            <text class="value">{{ item.contract_number || '未设置' }}</text>
          </view>
          <view class="info-row">
            <text class="label">合同金额：</text>
            <text class="value">{{ item.contract_money ? `¥${formatMoney(item.contract_money)}` : '未设置' }}</text>
          </view>
          <view class="info-row">
            <text class="label">创建时间：</text>
            <text class="value">{{ formatDate(item.createtime) }}</text>
          </view>
          
          <!-- 收款计划信息 -->
          <view class="payment-plan-info">
            <view class="plan-status">
              <text class="status-text">{{ hasPaymentPlan(item) ? '已设置收款计划' : '暂无收款计划' }}</text>
            </view>
            
            <!-- 收款计划详情 -->
            <view class="plan-details" v-if="hasPaymentPlan(item)">
              <view class="detail-row">
                <text class="detail-label">收款计划期数：</text>
                <text class="detail-value">{{ item.payment_plan_total }}期</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">收款计划已完成总数：</text>
                <text class="detail-value">{{ item.payment_plan_success || 0 }}期</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">收款计划异常总数：</text>
                <text class="detail-value">{{ item.payment_plan_error || 0 }}期</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">收款计划总金额：</text>
                <text class="detail-value">¥{{ formatMoney(item.payment_plan_total_amount || 0) }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">实收总金额：</text>
                <text class="detail-value">¥{{ formatMoney(item.actual_received_total_amount || 0) }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="item-actions">
          <button class="action-btn edit" @click.stop="editProject(item)">编辑项目</button>
          <button class="action-btn view" @click.stop="viewDetail(item)">收款计划</button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty" v-if="!loading && projectList.length === 0">
      <text class="empty-text">暂无数据</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>
    
    <!-- 底部TabBar -->
    <custom-tabbar :current="tabIndex" :tabList="tabList" />
  </view>
</template>

<script>
// 财务项目列表API
const getByFinanceProjectList = async (params = {}) => {
  return uni.request({
    url: 'https://data.web1995.top/api/project/getByFinanceProjectList',
    method: 'POST',
    data: params,
    header: { 'token': uni.getStorageSync('sc-token') || '' }
  })
}
import CustomTabbar from '@/components/custom-tabbar/CustomTabbar.vue'
import { getTabListByRole } from '@/utils/tabberList.js'

export default {
  components: { CustomTabbar },
  data() {
    return {
      tabList: [],
      tabIndex: 0,
      currentFilter: 'all',
      searchKeyword: '', // 搜索关键词
      loading: false,
      projectList: [],
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '已签约', value: '已签约' },
        { label: '异常', value: '异常' }
      ]
    }
  },
  
  onShow() {
    // 初始化TabBar
    const role = uni.getStorageSync('user-role');
    this.tabList = getTabListByRole(role);
    let currentPath = '';
    const pages = getCurrentPages();
    if (pages.length) {
      currentPath = pages[pages.length - 1].route || pages[pages.length - 1].__route__ || '';
    }
    this.tabIndex = this.tabList.findIndex(item => item.pagePath === currentPath);
    
    // 加载数据
    this.loadData()
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: 1,
          limit: 20,
          status: this.currentFilter === 'all' ? '' : this.currentFilter,
          keyword: this.searchKeyword.trim() // 添加搜索关键词
        }
        
        console.log('请求参数:', params)
        const res = await getByFinanceProjectList(params)
        console.log('接口返回完整数据:', res)
        console.log('接口返回状态码:', res.statusCode)
        console.log('接口返回数据:', res.data)
        
        if (res.statusCode === 200 && res.data && res.data.code === 1) {
          this.projectList = res.data.data?.list || []
          console.log('解析后的数据列表:', this.projectList)
          console.log('数据列表长度:', this.projectList.length)
          


        } else {
          console.error('接口返回错误:', res)
          uni.showToast({ title: res.data?.msg || '获取数据失败', icon: 'none' })
        }
      } catch (error) {
        console.error('加载失败:', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    
    // 筛选切换
    onFilterChange(filter) {
      this.currentFilter = filter
      this.loadData()
    },
    
    // 搜索方法
    async onSearch() {
      await this.loadData()
    },
    
    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/finance/detail?id=${item.id}&data=${encodeURIComponent(JSON.stringify(item))}`
      })
    },
    
    // 编辑项目
    editProject(item) {
      // 只传递必要的字段数据
      const formData = {
        id: item.id,
        project_name: item.project_name,
        customer_name: item.customer_name,
        manager_phone: item.manager_phone,
        site_manager: item.site_manager,
        site_manager_phone: item.site_manager_phone,
        customer_source: item.customer_source,
        customer_level: item.customer_level,
        input_address: item.input_address,
        production_quantity: item.production_quantity,
        product_model: item.product_model,
        remark: item.remark || ''
      };
      
      uni.navigateTo({
        url: `/pages/finance/form?id=${item.id}&data=${encodeURIComponent(JSON.stringify(formData))}`
      })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间'
      if (typeof dateStr === 'string' && dateStr.includes('-')) {
        return dateStr
      }
      return '时间格式错误'
    },
    
    // 获取状态文本
    getStatusText(status) {
      // 根据新API返回的中文状态直接显示
      return status || '未知状态'
    },
    

    
    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      if (amount === null || amount === undefined) return '0.00'
      if (isNaN(parseFloat(amount))) return '0.00'
      return parseFloat(amount).toFixed(2)
    },
    

    

    
    // 判断是否有收款计划
    hasPaymentPlan(item) {
      // 根据新API返回的字段判断是否有收款计划
      return item.payment_plan_total > 0 || 
             item.actual_received_total_amount > 0 ||
             item.settlement_amount > 0
    },
    



    

  }
}
</script>

<style lang="scss" scoped>
.page-content {
  padding: 20rpx;
  padding-bottom: 120rpx; /* 为TabBar留出空间 */
  background: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .search-input {
    flex: 1;
    height: 60rpx;
    border-radius: 8rpx;
    background: #f5f5f5;
    padding: 0 20rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
    border: 1rpx solid #e8e8e8;
  }
  
  .search-btn {
    width: 120rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
    border-radius: 8rpx;
    background: #52c41a;
    color: #fff;
    text-align: center;
    border: none;
  }
}

.filter-tabs {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
}

.filter-tab.active {
  background: #409eff;
  color: #fff;
}

.project-list {
  margin-bottom: 20rpx;
}

.project-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.project-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-text {
  font-size: 24rpx;
  color: #409eff;
  background: #e6f7ff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  white-space: nowrap;
  
  &.signed {
    color: #52c41a; // 已签约状态显示绿色
    background: #f6ffed;
  }
  
  &.error {
    color: #ff4d4f; // 异常状态显示红色
    background: #fff2f0;
  }
}

.item-content {
  .info-row {
    display: flex;
    margin-bottom: 16rpx;
    
    .label {
      width: 160rpx;
      color: #666;
      font-size: 28rpx;
      white-space: nowrap;
    }
    
    .value {
      flex: 1;
      color: #333;
      font-size: 28rpx;
    }
  }
}

/* 操作按钮样式 */
.item-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  flex: 1;
  height: 70rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.edit {
  background: #e6a23c;
  color: #fff;
}

.action-btn.view {
  background: #409eff;
  color: #fff;
}



.action-btn:active {
  opacity: 0.8;
}

/* 收款计划信息样式 */
.payment-plan-info {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.plan-status {
  margin-bottom: 16rpx;
  text-align: center;
}

.plan-status .status-text {
  font-size: 26rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  border: 1rpx solid #e9ecef;
  font-weight: 500;
}



.plan-details {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 16rpx;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.detail-value {
  font-size: 24rpx;
  color: #333;
  font-weight: 600;
}



.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: calc(100vh - 300rpx);
  padding: 100rpx 0;
  color: #999;
}

.loading {
  text-align: center;
  padding: 40rpx 0;
  color: #666;
}
</style>
